package ar.edu.itba.it.paw.domain;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.edu.itba.it.paw.domain.exceptions.DatabaseException;

@Component
public class ConnectionManager {
	
	private String username;
	private String password;
	private String connectionString;
	private Connection connection;
	
	@Autowired
	public ConnectionManager(String connectionString, String username, String password){
		this.connectionString = connectionString;
		this.username = username;
		this.password = password;
	}
	
	public Connection getConnection(){
		try {
			connection = DriverManager.getConnection(connectionString, username, password);
			connection.setAutoCommit(false);
		} catch (SQLException e) {
			throw new DatabaseException();
		}
		return connection;
	}
	
	public void closeConnection()
	{
		try
		{
			connection.commit();
			connection.close();
		}
		catch(Exception e)
		{
			throw new DatabaseException();
		}
	}
}
